package com.yiren.dbaa.module.practice_set.line.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.bean.LinePointBean;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.entity.ProjectEntity;
import com.yiren.backstage.db.dao.cache.DataCache;
import com.yiren.dbaa.R;
import com.yiren.dbaa.activity.BaseActivity;
import com.yiren.dbaa.global.GlobalApplication;
import com.yiren.dbaa.module.practice_set.PracticeCarSetActivity;
import com.yiren.dbaa.module.practice_set.line.contract.BaiduMapContract;
import com.yiren.dbaa.module.practice_set.line.contract.LineEditContract;
import com.yiren.dbaa.module.practice_set.line.presenter.BaiduMapPresenter;
import com.yiren.dbaa.module.practice_set.line.presenter.LineEditPresenter;
import com.yiren.dbaa.module.practice_set.line.view.dialog.BaiduMapInfoWindow;
import com.yiren.dbaa.module.practice_set.line.view.dialog.LineSaveDialog;
import com.yiren.dbaa.module.practice_set.line.view.dialog.LineViewLoadDialog;
import com.yiren.dbaa.util.CarSignalUtil;
import com.yiren.dbaa.view.adapter.line.PointNameListAdapter;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author lwb
 * @date : 2022/3/17 11:28
 * @description: 线路采集和预览页面
 */
public class LineEditActivity extends BaseActivity implements PointNameListAdapter.OnProjectActionListener, LineEditContract.View {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_left_info)
    LinearLayout llLeftInfo;
    @BindView(R.id.rg_point_action)
    RadioGroup rgPointAction;
    @BindView(R.id.tv_point_tip)
    TextView tvPointTip;
    @BindView(R.id.gv_select_project)
    GridView gvSelectProject;
    @BindView(R.id.ll_point_action)
    LinearLayout llPointAction;
    @BindView(R.id.tv_point_l)
    TextView tvPointL;
    @BindView(R.id.tv_point_c)
    TextView tvPointC;
    @BindView(R.id.tv_point_r)
    TextView tvPointR;
    @BindView(R.id.et_point_index)
    EditText etPointIndex;
    @BindView(R.id.btn_action_sure)
    Button btnActionSure;
    @BindView(R.id.mv_bmapView)
    MapView mapView;
    @BindView(R.id.cb_positioning)
    CheckBox cbPositioning;
    @BindView(R.id.tv_line_save)
    TextView tvLineSave;

    private BaiduMapContract.Presenter baiduMapPresenter;
    private BaiduMap baiduMap;
    private boolean isPositioning = true;   //是否跟随定位

    /*** 线路项目列表(待采集项目列表) */
    private List<ProjectEntity> projectList = new ArrayList<ProjectEntity>();
    /*** 项目列表适配器 */
    private PointNameListAdapter pointNameListAdapter;

    /*** 点位列表 */
    public List<LinePointBean> pointList = new ArrayList<LinePointBean>();

    /*** 当前的指令，默认为新增 */
    private int currentTag = 0;
    /*** 当前选择的点位索引 */
    private int currentPointIndex = -1;

    private Intent intent;
    /*** 1：新增线路 2：编辑线路 3：线路预览 */
    private int pageType;
    /*** 所选线路信息 */
    private LineInfoEntity lineInfo;
    private boolean isPartner;
    /*** 用于保存教练修改合伙人的点位 */
    private List<LinePointBean> tempLinePoints;

    private LineViewLoadDialog lineViewLoadDialog;//线路对话框控制器
    private LineEditContract.Presenter presenter;
    private UserParamConfigBean userParamConfig;
    private Gson gs = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_line_edit);
        ButterKnife.bind(this);
        initData();
        setData();
        addListenEvent();
    }

    private void initData() {
        isPartner = LoadConfigApi.loadUserParamConfig(this).isPartner();
        baiduMapPresenter = new BaiduMapPresenter(this);
        lineViewLoadDialog = new LineViewLoadDialog();
        presenter = new LineEditPresenter(this);
        userParamConfig = LoadConfigApi.loadUserParamConfig(this);
        baiduMap = baiduMapPresenter.LoadBaiduMap(mapView, isPositioning);
        tempLinePoints = new ArrayList<>();
    }

    private void setData() {
        intent = getIntent();
        pageType = intent.getIntExtra("pageType", 0);
        if (pageType == 1) {
            tvTitle.setText("采集线路");
            lineInfo = presenter.setLineInfo();
        } else if (pageType == 2) {
            tvTitle.setText("编辑线路");
            lineInfo = (LineInfoEntity) intent.getSerializableExtra("line");
            llLeftInfo.setVisibility(isPartner || lineInfo.getUserId() == userParamConfig.getUserInfo().getId() ? View.VISIBLE : View.GONE);
        } else {
            tvTitle.setText("线路预览");
            cbPositioning.setVisibility(View.GONE);
            llLeftInfo.setVisibility(View.GONE);
            tvLineSave.setVisibility(View.GONE);
            lineInfo = (LineInfoEntity) intent.getSerializableExtra("line");
        }
        if (rgPointAction.getVisibility() == View.VISIBLE)
            setRadioGroupChildDrawableTop();
        //获取线路点位
        presenter.getLinePoints(lineInfo, pointList, pageType, this);
    }

    /**
     * 设置Radiobutton的DrawableTop图片，这里动态设置因为要适配
     */
    private void setRadioGroupChildDrawableTop() {
        if (pageType == 1 || pageType == 2) {
            RadioButton rb;
            for (int i = 0; i < 6; i++) {
                rb = (RadioButton) rgPointAction.getChildAt(i);
                if (i == 0) {
                    CarSignalUtil.setTextDrawableTop(this, rb, R.drawable.line_point_add_selector);
                } else if (i == 1) {
                    CarSignalUtil.setTextDrawableTop(this, rb, R.drawable.line_point_insert_selector);
                } else if (i == 2) {
                    CarSignalUtil.setTextDrawableTop(this, rb, R.drawable.line_point_change_selector);
                } else if (i == 3) {
                    CarSignalUtil.setTextDrawableTop(this, rb, R.drawable.line_point_replace_selector);
                } else if (i == 4) {
                    CarSignalUtil.setTextDrawableTop(this, rb, R.drawable.line_point_correct_selector);
                } else {
                    CarSignalUtil.setTextDrawableTop(this, rb, R.drawable.line_point_delete_selector);
                }
            }
        }
    }

    @OnClick({R.id.iv_back, R.id.btn_action_sure, R.id.tv_line_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back: //返回
                if (pointList.size() > 0 && pageType != 3) {
                    lineViewLoadDialog.noSaveLine(this);
                } else {
                    recordLineBack();
                }
                break;
            case R.id.btn_action_sure://指令确认操作
                switch (currentTag) {
                    case 2://修改
                        if (currentPointIndex != -1) {
                            String indexStr = etPointIndex.getText().toString().trim();
                            if (StringUtils.isNotEmpty(indexStr)) {
                                presenter.modifyLinePoint(indexStr, currentPointIndex, pointList, this);
                                setChangeStatus();
                            } else {
                                MessageBox.show(this, "请填写指令序号");
                            }
                        } else {
                            MessageBox.show(this, "请在地图中选择要修改的点位！");
                        }
                        break;
                    case 4: //校准
                        if (currentPointIndex != -1) {
                            presenter.calibrationPoint(currentPointIndex, pointList, this);
                            setLeftInfoLayout(rgPointAction.getCheckedRadioButtonId());
                        } else {
                            MessageBox.show(this, "请在地图中选择要校准的点位！");
                        }
                        break;
                    case 5://删除
                        if (currentPointIndex != -1) {
                            presenter.deletePoint(currentPointIndex, pointList, this);
                            setLeftInfoLayout(rgPointAction.getCheckedRadioButtonId());
                        } else {
                            MessageBox.show(this, "请在地图中选择要删除的点位！");
                        }
                        break;
                }
                break;
            case R.id.tv_line_save: //线路保存
                if (null != pointList && pointList.size() > 0) {
                    lineInfo.setLinePoints(pointList);
                    if (isPartner) {
                        if (userParamConfig.getUserInfo().getId() != lineInfo.getUserId()) {
                            //合伙人修改其它人的线路
                            lineInfo.setUserId(userParamConfig.getUserInfo().getId());
                        } else {
                            //合伙人修改自己的线路
                            lineInfo.setPartneModifyVal(gs.toJson(pointList));
                        }
                    } else {
                        if (userParamConfig.getUserInfo().getId() != lineInfo.getUserId()) {
                            //教练修改合伙人的点位
                            if (tempLinePoints.size() > 0) {
                                presenter.saveCoachModify(lineInfo, tempLinePoints);
                            } else {
                                recordLineBack();
                                return;
                            }
                        } else {
                            //教练修改自己的线路
                            lineInfo.setCoachModifyVal(gs.toJson(pointList));
                        }
                    }
                    new LineSaveDialog(this, lineInfo, pageType).show();
                } else {
                    recordLineBack();
                }
                break;
        }
    }

    /**
     * checkbox点击事件
     */
    public void addListenEvent() {
        // 实时定位
        cbPositioning.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                cbPositioning.setBackground(getResources().getDrawable(R.drawable.btn_blue_radius_selector));
            } else {
                cbPositioning.setBackground(getResources().getDrawable(R.drawable.dialog_include_top_bottom_gray1_5));
            }
            baiduMap = baiduMapPresenter.LoadBaiduMap(mapView, isPositioning);
            if (pointList != null && pointList.size() > 0) {
                refreshBaiduMark();
            }
        });
        rgPointAction.setOnCheckedChangeListener((group, checkedId) -> setLeftInfoLayout(checkedId));
        baiduMapPresenter.baiduMapGpsListener();
        if (pageType != 3) baiduMap.setOnMarkerClickListener(onMarkerClickListener);
    }

    /**
     * 设置左边的显示样式
     *
     * @param checkedId
     */
    private void setLeftInfoLayout(int checkedId) {
        switch (checkedId) {
            case R.id.rb_point_add:    //新增
                currentTag = 0;
                tvPointTip.setVisibility(View.VISIBLE);
                tvPointTip.setText("请选择您需要新增的指令");
                gvSelectProject.setVisibility(View.VISIBLE);
                llPointAction.setVisibility(View.GONE);
                break;
            case R.id.rb_point_insert: //插入
                currentTag = 1;
                tvPointTip.setVisibility(View.VISIBLE);
                tvPointTip.setText("请在右侧地图选中需插入指令的前一个指令");
                gvSelectProject.setVisibility(View.VISIBLE);
                llPointAction.setVisibility(View.GONE);
                break;
            case R.id.rb_point_change: //修改
                currentTag = 2;
                tvPointTip.setVisibility(View.GONE);
                gvSelectProject.setVisibility(View.GONE);
                llPointAction.setVisibility(View.VISIBLE);
                btnActionSure.setText("确认修改");
                etPointIndex.setVisibility(View.VISIBLE);
                setChangeStatus();
                break;
            case R.id.rb_point_replace://替换
                currentTag = 3;
                tvPointTip.setVisibility(View.VISIBLE);
                tvPointTip.setText("请在右侧地图选中需替换的指令");
                gvSelectProject.setVisibility(View.VISIBLE);
                llPointAction.setVisibility(View.GONE);
                break;
            case R.id.rb_point_correct://校准
                currentTag = 4;
                tvPointTip.setVisibility(View.GONE);
                gvSelectProject.setVisibility(View.GONE);
                llPointAction.setVisibility(View.VISIBLE);
                btnActionSure.setText("确认校准");
                etPointIndex.setVisibility(View.INVISIBLE);
                if (currentPointIndex == -1) {
                    tvPointL.setText("请在右侧地图选中需校准的指令");
                    tvPointC.setVisibility(View.GONE);
                    tvPointR.setVisibility(View.GONE);
                    btnActionSure.setEnabled(false);
                } else {
                    tvPointL.setText("是否确认将指令");
                    tvPointC.setVisibility(View.VISIBLE);
                    tvPointC.setText((currentPointIndex + 1) + "." + pointList.get(currentPointIndex).getProjectInfo().getName());
                    tvPointR.setVisibility(View.VISIBLE);
                    tvPointR.setText("校准至当前定位");
                    btnActionSure.setEnabled(true);
                }
                break;
            case R.id.rb_point_delete: //删除
                currentTag = 5;
                tvPointTip.setVisibility(View.GONE);
                gvSelectProject.setVisibility(View.GONE);
                llPointAction.setVisibility(View.VISIBLE);
                btnActionSure.setText("确认删除");
                etPointIndex.setVisibility(View.INVISIBLE);
                if (currentPointIndex == -1) {
                    tvPointL.setText("请在右侧地图选中需删除的指令");
                    tvPointC.setVisibility(View.GONE);
                    tvPointR.setVisibility(View.GONE);
                    btnActionSure.setEnabled(false);
                } else {
                    tvPointL.setText("是否确认删除指令");
                    tvPointC.setVisibility(View.VISIBLE);
                    tvPointC.setText((currentPointIndex + 1) + "." + pointList.get(currentPointIndex).getProjectInfo().getName());
                    tvPointR.setVisibility(View.GONE);
                    btnActionSure.setEnabled(true);
                }
                break;
        }
    }

    /**
     * 设置修改的状态显示
     */
    private void setChangeStatus() {
        if (currentPointIndex == -1) {
            tvPointL.setText("请在右侧地图选中需操作的指令");
            tvPointC.setVisibility(View.GONE);
            tvPointR.setVisibility(View.GONE);
            etPointIndex.setText("");
            btnActionSure.setEnabled(false);
        } else {
            tvPointL.setText("将已选中指令");
            tvPointC.setVisibility(View.VISIBLE);
            tvPointC.setText((currentPointIndex + 1) + "." + pointList.get(currentPointIndex).getProjectInfo().getName());
            tvPointR.setVisibility(View.VISIBLE);
            tvPointR.setText("，序号修改为");
            btnActionSure.setEnabled(true);
        }
    }

    /**
     * 百度地图标记点击事件
     */
    BaiduMap.OnMarkerClickListener onMarkerClickListener = new BaiduMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(Marker marker) {
            currentPointIndex = marker.getZIndex();
            baiduMapPresenter.drawBaiduMarker(pointList, baiduMap, currentPointIndex);
            setLeftInfoLayout(rgPointAction.getCheckedRadioButtonId());
            LinePointBean linePoint = pointList.get(marker.getZIndex());
            LatLng latLng = marker.getPosition();
            InfoWindow currentInfoWindow = new InfoWindow(new BaiduMapInfoWindow(LineEditActivity.this, new BaiduMapInfoWindow.OnInfoWindowListener() {
                @Override
                public void onInfoWindowClose() {
                    currentPointIndex = -1;
                    refreshBaiduMark();
                    setLeftInfoLayout(rgPointAction.getCheckedRadioButtonId());
                }

                @Override
                public void onPointMove(int tzType, LinePointBean linePoint, int position) {
                    lineViewLoadDialog.numShowDialog(LineEditActivity.this, tzType, linePoint, position);
                    lineViewLoadDialog.setOnDialogClickListener(new LineViewLoadDialog.OnDialogClickListener() {
                        @Override
                        public void OnSureClickListener() {
                            if (!isPartner && lineInfo.getUserId() != userParamConfig.getUserInfo().getId()) {
                                //教练修改合伙人线路
                                tempLinePoints.add(linePoint);
                            }
                            refreshBaiduMark();
                        }
                    });
                }
            })
                    .getInfoWindowView(linePoint, marker.getZIndex(), baiduMap), latLng, 40);
            baiduMap.showInfoWindow(currentInfoWindow);
            return false;
        }
    };

    /**
     * 项目列表适配器点击回调
     */
    @Override
    public void onProjectAction(int position) {
        String access_token = LoadConfigApi.loadUserParamConfig(this).getAccessToken();
        if (StringUtils.isNotEmpty(access_token)) {
            switch (currentTag) {
                case 0:  //新增
                    presenter.addPoint(lineInfo, pointList, projectList.get(position), this);
                    break;
                case 1:  //插入
                    presenter.insertPoint(lineInfo, currentPointIndex, pointList, projectList.get(position), this);
                    break;
                case 3:  //替换
                    presenter.replacePoint(lineInfo, currentPointIndex, pointList, projectList.get(position), this);
                    break;
            }
        } else {
            GlobalApplication.getInstance().logOut(this);
        }
    }

    @Override
    public void loadProjectList() {
        //加载项目列表以及适配器
        projectList = presenter.getProjectList();
        if (null == projectList || projectList.size() == 0) {
            MessageBox.show(this, "项目列表为空！");
            return;
        }
        pointNameListAdapter = new PointNameListAdapter(this, projectList, this);
        gvSelectProject.setAdapter(pointNameListAdapter);
    }

    @Override
    public void refreshBaiduMap() {
        currentPointIndex = -1;
        lineInfo.setLinePoints(pointList);
        refreshBaiduMark();
    }

    /**
     * 加载百度地图标记
     */
    private void refreshBaiduMark() {
        baiduMapPresenter.drawBaiduMarker(pointList, baiduMap, currentPointIndex);
    }

    @Override
    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (pointList.size() > 0 && pageType != 3) {
                lineViewLoadDialog.noSaveLine(this);
            } else {
                recordLineBack();
            }
        }
        return true;
    }

    /**
     * 刷新缓存
     */
    private void refreshLineList() {
        runOnUiThread(() -> DataCache.refreshLineInfo(this, null));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        refreshLineList();
        recordLineBack();
        if (null != baiduMap) baiduMap.removeMarkerClickListener(onMarkerClickListener);
    }

    public boolean recordLineBack() {
        try {
            baiduMapPresenter.stopRefreshOption(false);
            mapView = null;
//            startActivity(new Intent(this, PracticeCarSetActivity.class));
            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

}